package com.fxz.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * jwt工具类
 */
 @Data
 @Component
 @ConfigurationProperties(prefix = "fxz.jwt")
public class JwtUtils {

    //token过期时间
    private long expire;
    //密钥
    private String secret;

    private String header;


    //生成JWT
    public String generateToken(String username){

        //创建时间
        Date date = new Date();
        //过期时间
        Date expireDate = new Date(date.getTime()+1000*expire);
        return Jwts.builder()
                .setHeaderParam("typ","jwt")
                //主体信息
                .setSubject(username)
                //创建时间
                .setIssuedAt(date)
                //过期时间
                .setExpiration(expireDate)
                //加密算法和密钥
                .signWith(SignatureAlgorithm.HS256,secret)
                .compact();
    }

    //解析JWT (Claims是请求体的内容)
    public Claims getClaimByToken(String jwt){
        try {
            return Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(jwt)
                    .getBody();
        }catch (Exception e){
            return null;
        }

    }

    //判断JWT是否过期
    public boolean isTokenExpired(Claims claims){
        return claims.getExpiration().before(new Date());
    }

}
